import { useEffect, useState } from "react";
import Navigate from "../components/Navigate.jsx";
import "./Management.css";
// 假设你有如下API
import { listReportsService, updateReportService } from "../api/AdminApi";

// 举报类型和处理状态选项
const reportedTypeOptions = [
  { value: "all", label: "全部" },
  { value: "user", label: "用户" },
  { value: "post", label: "帖子" },
  { value: "comment", label: "评论" },
];
const filterOptions = [
  { value: "all", label: "全部" },
  { value: "pending", label: "未处理" },
  { value: "processed", label: "已处理" },
];
const statusOptions = [
  { value: 2, label: "举报失败" },
  { value: 1, label: "举报成功" },
  { value: 0, label: "未处理" },
];

function ReportManagement() {
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    size: 10,
    total: 10,
  });
  const [searchParams, setSearchParams] = useState({
    reportedType: "all",
    filter: "",
    page: 1,
    pageSize: 10,
  });
  const [showProcessModal, setShowProcessModal] = useState(false);
  const [processingReport, setProcessingReport] = useState(null);
  const [processResult, setProcessResult] = useState("");

  // 查询
  const fetchReports = async () => {
    setLoading(true);
    const params = searchParams.reportedType === "all"
      ? {
        filter: searchParams.filter,
        page: searchParams.page,
        pageSize: searchParams.pageSize,
      }
      : { ...searchParams };
    try {
      const res = await listReportsService(params);
      if (res.status === 200) {
        setReports(res.data.records || []);
        setPagination({
          current: searchParams.page,
          size: searchParams.pageSize,
          total: res.data.total || 10,
        });
      }
    } catch (error) {
      console.error("查询举报列表失败:", error);
      setReports([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReports();
  }, [searchParams]);

  const handleSearchChange = (e) => {
    const { name, value } = e.target;
    setSearchParams((prev) => ({
      ...prev,
      [name]: value,
      page: 1,
    }));
  };

  const handleReset = () => {
    setSearchParams({
      reportedType: "all",
      filter: "",
      page: 1,
      pageSize: 10,
    });
  };

  const handlePageChange = (page) => {
    setSearchParams((prev) => ({
      ...prev,
      page: page,
    }));
  };

  const handlePageSizeChange = (size) => {
    setSearchParams((prev) => ({
      ...prev,
      pageSize: size,
      page: 1,
    }));
  };

  const handleProcess = (report) => {
    setProcessingReport(report);
    setProcessResult("");
    setShowProcessModal(true);
  };

  const handleProcessConfirm = async () => {
    if (!processingReport) return;
    const updatedParams = {
      reportId: processingReport.id,
      processResult: processResult || "无处理结果",
      status: processingReport.status,
    };
    try {
      const res = await updateReportService(updatedParams);
      if (res.status !== 200) {
        console.error("处理举报失败:", res.message);
        return;
      }
    } catch (error) {
      console.error("处理举报失败:", error);
      return;
    }
    fetchReports();
    setShowProcessModal(false);
    setProcessingReport(null);
    setProcessResult("");
  };

  // 格式化时间
  const formatDate = (dateStr) => {
    if (!dateStr) return "-";
    return new Date(dateStr).toLocaleString("zh-CN");
  };

  return (
    <div className="admin-layout">
      <Navigate activeItem="举报管理" />
      <div className="main-content">
        <div className="management-container">
          <div className="header">
            <h2>举报管理</h2>
          </div>

          {/* 查询表单 */}
          <div className="search-form">
            <div className="form-group">
              <label>举报类型</label>
              <select
                name="reportedType"
                value={searchParams.reportedType}
                onChange={handleSearchChange}
                className="form-select"
              >
                {reportedTypeOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <label>处理状态</label>
              <select
                name="filter"
                value={searchParams.filter}
                onChange={handleSearchChange}
                className="form-select"
              >
                {filterOptions.map((opt) => (
                  <option key={opt.value} value={opt.value}>
                    {opt.label}
                  </option>
                ))}
              </select>
            </div>
            <div className="form-group">
              <button className="btn btn-secondary" onClick={handleReset}>
                重置
              </button>
            </div>
          </div>

          {/* 举报表格 */}
          <div className="table-container">
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>举报类型</th>
                  <th>被举报ID</th>
                  <th>举报人ID</th>
                  <th>状态</th>
                  <th>举报时间</th>
                  <th>处理时间</th>
                  <th>处理结果</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={9} style={{ textAlign: "center" }}>加载中...</td>
                  </tr>
                ) : reports.length === 0 ? (
                  <tr>
                    <td colSpan={9} style={{ textAlign: "center" }}>暂无数据</td>
                  </tr>
                ) : (
                  reports.map((item) => (
                    <tr key={item.id}>
                      <td>{item.id}</td>
                      <td>
                        {item.reportedType === "user"
                          ? "用户"
                          : item.reportedType === "post"
                          ? "帖子"
                          : item.reportedType === "comment"
                          ? "评论"
                          : "-"}
                      </td>
                      <td>{item.reportedId}</td>
                      <td>{item.reporterId}</td>
                      <td>
                        <span
                          className={
                            item.status === 2
                              ? "status-badge status-normal"
                              : item.status === 1
                              ? "status-badge status-processing"
                              : "status-badge status-banned"
                          }
                        >
                          {statusOptions.find(opt => opt.value === item.status)?.label || "未知"}
                        </span>
                      </td>
                      <td>{formatDate(item.createTime)}</td>
                      <td>{formatDate(item.processTime)}</td>
                      <td>{item.processResult || "-"}</td>
                      <td>
                        <button className="btn btn-primary" onClick={() => handleProcess(item)}>
                          处理
                        </button>
                      </td>
                        
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          {/* 处理举报弹窗 */}
          {showProcessModal && processingReport && (
            <div className="modal-overlay" onClick={() => setShowProcessModal(false)}>
              <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <h2>处理举报</h2>
                </div>
                <div className="modal-body">
                  <div className="detail-section">
                    <h3 className="section-title">举报信息</h3>
                    <div className="detail-item">
                      <label className="detail-label">ID</label>
                      <div className="detail-value">{processingReport.id}</div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">举报类型</label>
                      <div className="detail-value">
                        {processingReport.reportedType === "user"
                          ? "用户"
                          : processingReport.reportedType === "post"
                          ? "帖子"
                          : processingReport.reportedType === "comment"
                          ? "评论"
                          : "-"}
                      </div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">被举报ID</label>
                      <div className="detail-value">{processingReport.reportedId}</div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">举报人ID</label>
                      <div className="detail-value">{processingReport.reporterId}</div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">举报原因</label>
                      <div className="detail-value">{processingReport.reason}</div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">状态</label>
                      <div className="detail-value">
                        <span
                          className={
                            processingReport.status === 2
                              ? "status-badge status-normal"
                              : processingReport.status === 1
                              ? "status-badge status-processing"
                              : "status-badge status-banned"
                          }
                        >
                          {statusOptions.find(opt => opt.value === processingReport.status)?.label || "未知"}
                        </span>
                      </div>
                    </div>
                    <div className="detail-item">
                      <label className="detail-label">举报时间</label>
                      <div className="detail-value">{formatDate(processingReport.createTime)}</div>
                    </div>
                  </div>
                  <div className="detail-section">
                    <h3 className="section-title">处理结果</h3>
                    <div className="detail-item">
                      <label className="detail-label">处理状态</label>
                      <select
                        className="edit-input"
                        value={processingReport.status}
                        onChange={e =>
                          setProcessingReport({
                            ...processingReport,
                            status: Number(e.target.value),
                          })
                        }
                      >
                        {statusOptions.map(opt => (
                          <option key={opt.value} value={opt.value}>
                            {opt.label}
                          </option>
                        ))}
                      </select>
                    </div>
                    <textarea
                      className="edit-input"
                      placeholder="请输入处理结果"
                      value={processResult}
                      onChange={e => setProcessResult(e.target.value)}
                      rows={4}
                    />
                  </div>
                </div>
                <div className="modal-footer">
                  <button className="btn btn-primary" onClick={() => handleProcessConfirm()}>
                    确认
                  </button>
                  <button className="btn btn-secondary" onClick={() => setShowProcessModal(false)}>
                    取消
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* 分页 */}
          <div className="pagination-container">
            <div className="pagination-info">共 {pagination.total} 条数据</div>
            <div className="pagination-controls">
              <button
                onClick={() => handlePageChange(pagination.current - 1)}
                disabled={pagination.current === 1}
                className="pagination-btn"
              >
                ‹
              </button>
              {/* 简单分页数字 */}
              {[...Array(Math.ceil(pagination.total / pagination.size)).keys()].map((i) => (
                <button
                  key={i + 1}
                  className={`pagination-btn ${pagination.current === i + 1 ? "active" : ""}`}
                  onClick={() => handlePageChange(i + 1)}
                >
                  {i + 1}
                </button>
              ))}
              <button
                onClick={() => handlePageChange(pagination.current + 1)}
                disabled={pagination.current === Math.ceil(pagination.total / pagination.size)}
                className="pagination-btn"
              >
                ›
              </button>
              <div className="pagination-jump">
                <select
                  value={pagination.size}
                  onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                >
                  {[10, 20, 50, 100].map((size) => (
                    <option key={size} value={size}>
                      {size} 条/页
                    </option>
                  ))}
                </select>
                <span>跳至</span>
                <input
                  type="number"
                  min={1}
                  max={Math.ceil(pagination.total / pagination.size)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      const page = Number(e.target.value);
                      if (page >= 1 && page <= Math.ceil(pagination.total / pagination.size)) {
                        handlePageChange(page);
                      }
                    }
                  }}
                  placeholder="页码"
                />
                <span>页</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default ReportManagement;